import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
#模拟最小二乘法过程
if __name__=="__main__":
    nsample=100
    x = np.linspace(0, 10, nsample)
    x1=x
    x=sm.add_constant(x)
    beta = np.array([1, 10])
    e = np.random.normal(size=nsample)
    y = np.dot(x, beta) + e
    model = sm.OLS(y, x)
    results = model.fit()
    print(results.params)
    y_fitted = results.fittedvalues
    fig, ax = plt.subplots(figsize=(8, 6))
    ax.plot(x1, y, 'o', label='data')
    ax.plot(x1, y_fitted, 'r--.', label='OLS')
    ax.axis((-0.05, 2, -1, 25))
    plt.show()